package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Course;
import model.User;
import model.UserCourse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import service.impl.JSONDecoder;
import dao.UserCourseDAO;

/**
 * Servlet implementation class CourseData
 */
public class CourseData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CourseData() {
		super();
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-cache");

		HttpSession session = request.getSession(true);
		User user = (User) (session.getAttribute("currentSessionUser"));
		try {
			String action = request.getParameter("action");
			Long semesterId = Long.parseLong(request.getParameter("semesterId"));
			if (action.equals("save")) {
				String courses = request.getParameter("courses");
				List<UserCourse> userCourses = JSONDecoder.getUserCourses(courses, /*user.getId()*/3L, semesterId);
				UserCourseDAO.save(userCourses);
			} else if (action.equals("get")) {
				// Get for select
				// TODO add UserCourseDAO.get(user.getId());
				List<Course> courses = UserCourseDAO.get(3L, semesterId);
				PrintWriter outWriter = response.getWriter();
				JSONObject coursesList = new JSONObject();
				JSONArray jsonList = new JSONArray();

				for (Course course : courses) {
					JSONObject jsonCourse = new JSONObject();
					jsonCourse.put("key", course.getCode());
					jsonCourse.put("nameValue", course.getName());
					jsonList.add(jsonCourse);
				}
				coursesList.put("courses", jsonList);
				outWriter.write(coursesList.toString());
			}
		} catch (Throwable theException) {
			System.out.println(theException);
		}

	}

}
